package com.shanzmoo.admin.manager.store;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.shanzmoo.core.util.BCryptUtils;
import com.shanzmoo.db.store.entity.StoreMemberEntity;
import com.shanzmoo.db.store.entity.query.StoreMemberQuery;
import com.shanzmoo.db.store.entity.vo.StoreMemberVO;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.db.store.service.IStoreMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 仓储客户 管理器
 *
 * @author Gzhao 2021-03-08
 */
@Slf4j
@Component
public class StoreMemberManager {
    /**
     * 仓储用户初始密码
     */
    private static final String INIT_PASSWORD = "777777";

    @Autowired
    private IStoreMemberService storeMemberService;

    /**
     * 分页查询
     */
    public PageRespBase<StoreMemberVO> queryPage(StoreMemberQuery query) {
        Page page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<StoreMemberVO> reList = storeMemberService.queryPageList(query);

        PageRespBase<StoreMemberVO> result = PageRespBase.create(page, reList);
        PageHelper.clearPage();
        return result;
    }

    /**
     * 新增仓储用户
     *
     * @author Gzhao 2021/3/14
     * @param
     * @return
     */
    public void addMember(StoreMemberEntity entity, Integer currentUserId) {
        entity.setPassword(BCryptUtils.encodePassword(INIT_PASSWORD));
        entity.setCreateUser(currentUserId);
        storeMemberService.save(entity);
    }

    /**
     * 重置密码
     *
     * @author Gzhao 2021/3/14
     * @param id    用户id
     * @param currentUserId
     * @return
     */
    public void restPassword(Integer id, Integer currentUserId) {
        StoreMemberEntity member = storeMemberService.getById(id);
        Assert.isTrue(ObjectUtil.isNotNull(member), "密码重置失败");

        member.setPassword(BCryptUtils.encodePassword(INIT_PASSWORD));
        member.setUpdateUser(currentUserId);
        storeMemberService.updateById(member);
    }

    /**
     * 启用（禁用）
     *
     * @author Gzhao 2021/3/14
     * @param
     * @return
     */
    public void updateStatus(Integer id, Integer currentUserId) {
        StoreMemberEntity member = storeMemberService.getById(id);
        Assert.isTrue(ObjectUtil.isNotNull(member), "未获取到仓储用户");

        member.setStatus(!member.getStatus());
        member.setUpdateUser(currentUserId);
        storeMemberService.updateById(member);
    }
}
